<?php
namespace app\apisell\controller\admin;

use app\apisell\service\order\OrderService;
use app\apisell\service\settle\SettleService;
use app\common\controller\BaseController;
use app\common\utils\Res;
use Exception;
use think\facade\Db;

/**
 * 参数设置
 */
class Settle extends BaseController
{
    public function index()
    {
        $param = $this->request->post();
        $result = SettleService::list();
        return $result;
    }
    /**
     * 添加结算参数设置
     * 该方法用于更新微信支付的商户设置，并可配置是否开启自动结算以及结算周期
     * 主要涉及两个数据库表：xh_sell_sys_wechat_pay_disposition（微信支付配置）和xh_sell_sys_settings（系统设置）
     */
    public function addSettle()
    {
        // 获取前端POST请求中的参数
        $param = $this->request->post();
        // 组装微信支付配置数据
        $data['mchid'] = $param['mchid'];
        $data['appid'] = $param['appid'];
        $data['app_secret'] = $param['app_secret'];
        $data['wx_key'] = $param['wx_key'];
        $data['deal_day'] = $param['deal_day'];
        $data['set_hour'] = $param['set_hour'];
        $data['limited_prompt_msg'] = $param['limited_prompt_msg'];
        $data['old_prompt_msg'] = $param['old_prompt_msg'];
        $data['new_prompt_msg'] = $param['new_prompt_msg'];
        // 记录创建时间
        $data['create_time'] = date('Y-m-d H:i:s',time());
        
        // 删除现有的微信支付配置和系统设置，准备更新
        Db::table('xh_sell_sys_wechat_pay_disposition')->delete(true);
        
        try {
            // 插入新的微信支付配置
            Db::table('xh_sell_sys_wechat_pay_disposition')->insert($data);
          
            // 返回成功消息
            return Res::ok('添加成功');
        }catch (Exception $e){
            // 异常处理，返回错误信息
            return Res::error($e->getMessage().$e->getLine());
        }
    }
    
    //团购分享设置
    public function groupSettle()
    {
        $param = $this->request->post();
        
        $has = Db::table('xh_sell_set_up')->where('type',3)->where('desc',1)->count();
        $keys = array_keys($param);
        $label = [
            $param['label0'],
            $param['label1'],
            $param['label2']
        ];
        unset($param['label0']);
        unset($param['label1']);
        unset($param['label2']);
        $params_num = count($param);
        $data = [];
        for($i=0;$i<$params_num;$i++){
            $data[$i]['type'] = 3;
            $data[$i]['desc'] = 1;
            $data[$i]['key'] = $keys[$i];
            $data[$i]['value'] = $param[$keys[$i]];
            $data[$i]['label'] = $label[$i];
        }
        
        try {
            if($has == 0){
                Db::table('xh_sell_set_up')->insertAll($data);
                return Res::ok('添加成功');
            }else{
                foreach ($data as $v){
                    Db::table('xh_sell_set_up')->where('type',3)->where('desc',1)->where('key',$v['key'])->update([
                        'value' => $v['value'],
                    ]);
                }
                return Res::ok('更新成功');
            }
        }catch (Exception $e){
            return Res::error($e->getMessage().$e->getLine());
        }
    }
    
    //获取团购分享设置
    public function groupSettleInfo()
    {
        $result = Db::table('xh_sell_set_up')->where('type',3)->where('desc',1)->select()->toArray();
        $data = [];
        foreach ($result as $v){
            if($v['key'] == 'title'){
                $data['title'] = $v['value'];
            }
            if($v['key'] == 'img'){
                $data['img'] = $v['value'];
            }
            if($v['key'] == 'status'){
                $data['status'] = (int)$v['value'];
            }
        }
        return Res::ok($data);
    }
    
    //企微标签设置
    public function settleQiweiTags()
    {
        $param = $this->request->post();

        $has = Db::table('xh_sell_set_up')->where('type',3)->where('desc',2)->count();

        $label = [
            $param['status_name0'],
            $param['status_name1'],
            $param['status_name2'],
            $param['status_name3'],
            $param['status_name4']
        ];
        unset($param['status_name0']);
        unset($param['status_name1']);
        unset($param['status_name2']);
        unset($param['status_name3']);
        unset($param['status_name4']);
        $keys = array_keys($param);
        $params_num = count($param);
        $data = [];
        for($i=0;$i<$params_num;$i++){
            $data[$i]['type'] = 3;
            $data[$i]['desc'] = 2;
            $data[$i]['key'] = $keys[$i];
            $data[$i]['value'] = $param[$keys[$i]];
            $data[$i]['label'] = $label[$i];
        }
        
        try {
            if($has == 0){
                Db::table('xh_sell_set_up')->insertAll($data);
                return Res::ok('添加成功');
            }else{
                foreach ($data as $v){
                    Db::table('xh_sell_set_up')->where('type',3)->where('desc',2)->where('key',$v['key'])->update([
                        'value' => $v['value'],
                    ]);
                }
                return Res::ok('更新成功');
            }
        }catch (Exception $e){
            return Res::error($e->getMessage().$e->getLine());
        }
    }
    
    //获取企微标签设置
    public function getQiweiTags()
    {
        $result = Db::table('xh_sell_set_up')->where('type',3)->where('desc',2)->select()->toArray();
        $data = [];
        foreach ($result as $v) {
            if($v['key'] == 'tags0'){
                $data['tags0'] = $v['value'];
            }
            if($v['key'] == 'tags1'){
                $data['tags1'] = $v['value'];
            }
            if($v['key'] == 'tags2'){
                $data['tags2'] = $v['value'];
            }
            if($v['key'] == 'tags3'){
                $data['tags3'] = $v['value'];
            }
            if($v['key'] == 'tags4'){
                $data['tags4'] = $v['value'];
            }
        }
        return Res::ok($data);
    }
    
    //下单以后  获取领课标题 提示语
    public function getLingkeTitle()
    {
        $result = Db::table('xh_sell_group_lingke_title')->select()->toArray();
        $data = [];
        foreach ($result as $v) {
            $data['status' . $v['type']] = $v['title'];
        }


        $result = Db::table('xh_sell_set_up')->where(array('desc'=>4))->select()->toArray();
        $data = $result;

        return Res::ok($data);
    }
    //更新领课标题 提示语
    public function addLingkeTitle()
    {
        $param = $this->request->post();

        Db::table('xh_sell_group_lingke_title')->delete(true);
        $data = [
            [
                'title' => $param['status1'],
                'type' => 1,
            ],
            [
                'title' => $param['status2'],
                'type' => 2,
            ],
        ];

        try {
            foreach($param  as $k  => $v){
                $update_data['value'] = $v['value'];
                db::name('sell_set_up')->where('id = '.$v['id'])->save($update_data);
            }
            return Res::ok('更新成功');
        }catch (Exception $e){
            return Res::error($e->getMessage().$e->getLine());
        }

    }
    
    public function getPromptList()
    {
        $result = Db::table('xh_sell_set_up')->where('type',3)->where('desc',4)->select()->toArray();
        $data = [];
        foreach ($result as $v){
            if ($v['key'] == 'limited_prompt_msg'){
                $data['limited_prompt_msg'] = $v['value'];
            }elseif ($v['key'] == 'old_prompt_msg'){
                $data['old_prompt_msg'] = $v['value'];
            }elseif ($v['key'] == 'new_prompt_msg'){
                $data['new_prompt_msg'] = $v['value'];
            }
            
        }
            
        return Res::ok($data);
    }

    /**
     * 更新提示语设置
     * @return \think\response\Json
     */
    public function getSettlePrompt()
    {
        $param = $this->request->post();
    
        try {
            // 批量更新
            $updates = [
                ['key' => $param['relist1'], 'type' => 3, 'value' => $param['limited_prompt_msg'], 'desc' => 4],
                ['key' => $param['relist2'], 'type' => 3, 'value' => $param['old_prompt_msg'], 'desc' => 4],
                ['key' => $param['relist3'], 'type' => 3, 'value' => $param['new_prompt_msg'], 'desc' => 4],
            ];
    
            foreach ($updates as $update) {
                
                Db::table('xh_sell_set_up')
                    ->where('key', $update['key'])
                    ->update([
                        'type' => $update['type'],
                        'value' => $update['value'],
                    ]);
            }
            return  Res::ok('更新成功');
        } catch (\Exception $e) {
            // 记录日志或返回错误信息
            return Res::error('Database update failed'.$e->getMessage());
        }
    }

}
